package firstping.cron;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions.Method;


import firstping.data.QnAPersistenceManager;
import firstping.model.Domain;

@SuppressWarnings("serial")
public class CronDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		
		Query query = psm.newQuery(Domain.class);
		query.setFilter("update <= dateParam && active=='1'");
		query.declareParameters("java.util.Date dateParam");
		@SuppressWarnings("unchecked")
		List<Domain> list = (List<Domain>) query.execute(new java.util.Date());
		if(list.size() > 0)
		{
			Date date = new Date();
			if(list.get(0).getEndDate().getTime() < date.getTime())
			{
				list.get(0).setActive("0");
				psm=JDOHelper.getPersistenceManager(list.get(0));
				psm.currentTransaction().begin();
				psm.makePersistent(list.get(0));
				psm.currentTransaction().commit();
			}
			Queue queue = QueueFactory.getDefaultQueue();
			for(int i=0;i<list.size();i++)
			{
				queue.add(withUrl("/check").method(Method.GET).param("name", list.get(i).getName()).param("email", list.get(i).getEmail()));
			}
		}
	}

}
